﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml.Linq;
using MusicExplorer.Data;
using MusicExplorer.Helper;
using MusicExplorer.Internals;
using MusicExplorer.WebRepository.Service;
using MusicExplorer.Wrappers;

namespace MusicExplorer.ViewModel.Popup
{
    public class YoutubeWebRepositoryPreferencesViewModel : WebRepositoryGroupPreferencesViewModel
    {
        private const string m_xml_namespace = "http://www.w3.org/2005/Atom";
        private const string m_xml_yt_namespace = "http://gdata.youtube.com/schemas/2007";
        private const string m_url_SEARCHARTISTS = "https://gdata.youtube.com/feeds/api/channels?q={0}&start-index={1}&max-results={2}&v=2";

        public YoutubeWebRepositoryPreferencesViewModel(MainWindowViewModel parent, WebRepositoryGroupWrapper groupWrapper)
            : base(parent, groupWrapper)
        {
        }

        public override bool CanAddEntity { get { return true; } }

        protected override bool SearchEntityFromTerms()
        {
            SearchedEntitiesLog.SetLog("Search in progress...", LogTypeEnum.Loading);

            if (m_tokenSearchEntity.IsCancellationRequested)
                return false;

            var repos = SearchRepositories();

            try
            {
                repos.Wait();
            }
            catch (Exception ex)
            {
                //if (!(ex is AggregateException || ex is OperationCanceledException))
                SearchedEntitiesLog.LogError(ex);
                return false;
            }

            if (m_tokenSearchEntity.IsCancellationRequested)
                return false;

            if (repos.Result.Count > 0)
            {
                MusicExplorerHelper.ExecuteInUIThread(() =>
                {
                    foreach (var repo in repos.Result)
                    {
                        if (Entities.Select(e => e.Entity as WEB_REPOSITORY).Count(wr => wr.web_repo_key == repo.web_repo_key) == 0)
                        {
                            var a = new DetailTreeItemWrapper(repo);
                            SearchedEntitiesToAdd.Add(a);
                        }
                    }
                    LaunchTaskFromScrollViewerState();
                });
            }
            else m_nothingToSearch = true;

            SearchedEntitiesLog.ResetLog();
            return true;
        }

        private async Task<List<WEB_REPOSITORY>> SearchRepositories()
        {
            var repos = new List<WEB_REPOSITORY>();

            m_tokenSearchEntity.Token.ThrowIfCancellationRequested();

            var xmlEntries = await ServiceWebRepository.GetUrlDataAsync(m_webClientSearchEntity, string.Format(m_url_SEARCHARTISTS, m_currentSearchTerms, 1 + (m_currentPageSearch - 1) * 10, 10));
            XDocument doc = XDocument.Parse(xmlEntries);
            XNamespace nmsp = m_xml_namespace;
            XNamespace yt = m_xml_yt_namespace;
            var entries = doc.Root.Elements(nmsp + "entry");

            foreach (var entry in entries)
            {

                var title = entry.Element(nmsp + "title").Value;
                var author = HttpUtility.HtmlDecode(entry.Element(nmsp + "author").Element(nmsp + "name").Value);
                var userId = entry.Element(nmsp + "author").Element(yt + "userId").Value;

                WEB_REPOSITORY repo = new WEB_REPOSITORY()
                {
                    web_repo_id = Guid.NewGuid(),
                    web_repo_key = userId,
                    web_repo_name = title != author ? title + " - " + author : title,
                    type_web_repo_id = ServiceWebRepository.GetTypeWebRepository(TypeWebRepository.YoutubeChannel).type_web_repo_id
                };

                repos.Add(repo);
            }

            return repos;
        }
    }
}
